<template>
	<view class="pageAll">

		<scroll-view class="scrollView" scroll-y="true" :scroll-into-view="scrollId"
		 @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd">
			<view class="scrollDown" :class="{'scroll-downwarp-reset':scrollObject.isReset}" :style="{'height': scrollObject.downHeight+'px', 'position': 'relative', 'overflow': 'hidden', '-webkit-transition': scrollObject.isReset?'height 1000ms':''}">
				<view class="downwarp-progress" :class="{'scroll-rotate':scrollObject.isDownLoading}"></view>
				<view class="downwarp-tip">{{scrollObject.scrollTip}}</view>
			</view>

			<view v-for="(item, index) in messList" :id="'mess'+index" :key="index" class="chatBox">
				<chatBox v-if="item.type === 1" :indexID="index" :message="item.message" :type="item.userType" @reSend="reSend"
				 :isWarn="item.isSend" />
				<chatImg v-if="item.type === 2" :type="item.userType" :imagePath="item.message" @click.native="previewImg(item.message)"
				 :indexID="index" @reSend="reSend" :isWarn="item.isSend" />
				<view v-if="item.type === 3">
					<hbtime :date="item.date" />
					<hbNotice :info="item" />
				</view>
			</view>
		</scroll-view>

		<view class="bottomView">

			<view class="bottomViewInput">
				<input type="text" v-model="mess" @confirm="sendMess" confirm-type="send">
			</view>
			<view class="bottomViewBtn">
				<image :src="tupain" @click="getImage"></image>
				<button @click="sendMess" hover-class="subActive">
					发送
				</button>
			</view>

		</view>
	</view>
</template>

<script>
	import hbtime from '../../../components/message/time.vue'
	import hbNotice from '../../../components/message/hbNotice.vue'
	import chatBox from '../../../components/message/chatBox.vue'
	import chatImg from '../../../components/message/chatImg.vue'
	import MescrollUni from "@/components/mescroll-uni/mescroll-uni.vue";
	import {
		WebSocket
	} from '@/utils/webSocket.js'
	import {
		uploadFile
	} from '@/utils/alioss.js'
	import {
		formatTime
	} from '@/utils/tools.js'

	let webSocket = new WebSocket()
	let inter = null
	export default {
		data() {
			return {
				tupain: require('../../../static/message/tupian.png'),
				notice: [{
					title: '红标消息',
					date: '1563163358',
					content: '您的账号“王小明”进行了网站登录操作， 如有疑问。 请联系客服',
					type: 3
				}, ],
				mess: '',
				messList: [], // 显示的聊天信息
				scrollId: '',
				// imagePath: require('../../../static/index/sopFile.png'),
				imgPaths: [],
				scrollTop: null,
				saveMessList: [], // 此次聊天内容
				// 下拉刷新的配置
				downOption: {
					use: true, // 是否启用下拉刷新; 默认true
					auto: false, // 是否在初始化完毕之后自动执行下拉刷新的回调; 默认true
				},
				// 上拉加载的配置
				upOption: {
					use: false, // 是否启用上拉加载; 默认true
					auto: false, // 是否在初始化完毕之后自动执行上拉加载的回调; 默认true
					isLock: true, // 是否锁定下拉刷新如果配置true,则会锁定不可下拉,可通过调用mescroll.lockDownScroll(false)解锁
				},
				messageNum: 6, // 每次加载的数据条数
				mescrollSelf: null,
				scrollObject: {
					startPoint: null, // 起始点
					lastPoint: null, // 结束点
					movePoint: null, // touchmove当前点
					movingDistance: 100, // 移动触发加载的距离
					isRefresh: false, // 是否刷新
					downHeight: 0, // 下滑距离 ，最大为movingDistance
					scrollTip: '下拉加载更多', // 下滑文字提示
					isDownLoading: false, // 显示加载动画
					isReset: false, // 是否重置
				},
				currPage: 0,
				moveTime:null,
				moveTimeDiff:null,
				fps:40,
			}
		},
		methods: {

			throttle(fn, interval) {
				var enterTime = 0; //触发的时间
				var gapTime = interval || 300; //间隔时间，如果interval不传，则默认300ms
				console.log(gapTime, '11111111111111')
				var context = this;
				return (function() {
					
					var backTime = +new Date(); //第一次函数return即触发的时间
					console.log(backTime, '2222222222222')
					if (backTime - enterTime > gapTime) {
						console.log(backTime, '333333333333333333')
						fn.call(context, arguments);
						enterTime = backTime; //赋值给第一次触发的时间，这样就保存了第二次触发的时间
					}
				})();
			},
			scroll(e) {
				// const topHeight = e.detail.scrollTop
				// this.scrollTop = topHeight
			},
			// 触摸滑动开始
			touchStart(e) {
				e.preventDefault
				this.scrollObject.startPoint = e.touches ? e.touches[0].pageY : e.clientY
				console.log(this.scrollObject.startPoint, '123456789')
				// console.log(e, 'touchStart')
			},
			// 触摸滑动
			touchMove(e) {
				let t = new Date().getTime();
				if(this.moveTime && t - this.moveTime < this.moveTimeDiff){ // 小于节流时间,则不处理
					return;
				}else{
					this.moveTime = t
					this.moveTimeDiff = 1000/this.fps
				}
				// this.throttle(() => {
					this.scrollObject.movePoint = e.touches ? e.touches[0].pageY : e.clientY
					const tempHeight = this.scrollObject.movePoint - this.scrollObject.startPoint
					this.scrollObject.downHeight = tempHeight >= this.scrollObject.movingDistance ? this.scrollObject.movingDistance :
						tempHeight
					if (!this.scrollObject.isRefresh) {
						if (this.scrollObject.downHeight >= this.scrollObject.movingDistance) {
							this.$set(this.scrollObject, 'isDownLoading', true)
							this.$set(this.scrollObject, 'isRefresh', true)
							this.$set(this.scrollObject, 'isReset', true)
						}
					}
					// console.log(e, '123456789')
				// }, 1000)

				// console.log(e, 'touchMove')
			},
			// 触摸滑动结束
			touchEnd(e) {
				if (this.scrollObject.isRefresh) {
					this.getHis()
						.then(() => {
							this.$set(this.scrollObject, 'isDownLoading', false)
							this.$set(this.scrollObject, 'downHeight', 0)
							this.$set(this.scrollObject, 'isReset', false)
							this.$set(this.scrollObject, 'isRefresh', false)
						})
						.catch(() => {
							this.$set(this.scrollObject, 'isDownLoading', false)
							this.$set(this.scrollObject, 'downHeight', 0)
							this.$set(this.scrollObject, 'isReset', false)
							this.$set(this.scrollObject, 'isRefresh', false)
						})
				} else {
					this.$set(this.scrollObject, 'isReset', false)
					this.$set(this.scrollObject, 'isDownLoading', false)
					this.$set(this.scrollObject, 'downHeight', 0)
					this.$set(this.scrollObject, 'isRefresh', false)
				}
			},
			//  获取历史消息
			getHis(isNeedToast = true) {
				return new Promise((resolve, reject) => {
					uni.getStorage({
						key: 'chatHistory',
						success: (res) => {
							const tempRes = JSON.parse(JSON.stringify(res.data))
							let tempResLength = null
							if (tempRes.length - this.currPage * this.messageNum > this.messageNum) {
								tempResLength = tempRes.length - this.currPage * this.messageNum
							} else if ((this.currPage - 1) * this.messageNum - tempRes.length < this.messageNum) {
								tempResLength = tempRes.length - this.currPage * this.messageNum
							} else {
								tempResLength = -1
							}
							if (tempResLength >= 1) {
								let messLength = null
								if (tempResLength - this.messageNum > 0) {
									messLength = tempResLength - this.messageNum
								} else {
									messLength = 0
								}
								for (let i = tempResLength - 1; i >= messLength; i--) {
									this.messList.unshift(tempRes[i])
								}
								this.currPage++
							} else {
								if (isNeedToast) {
									uni.showToast({
										title: '历史记录为空',
										icon: 'none',
										duration: 1500,
									})
								}

							}
							resolve()
						},
						fail: () => {
							if (isNeedToast) {
								uni.showToast({
									title: '历史记录为空',
									icon: 'none',
									duration: 1500,
								})
							}
							reject()
						}
					})
				})
			},
			//  预览图片
			previewImg(curr) {

				let imgLists = []
				for (let index in this.messList) {
					if (this.messList.hasOwnProperty(index)) {
						if (this.messList[index].type === 2) {
							imgLists.push(this.messList[index].message)
						}
					}
				}

				uni.previewImage({
					current: curr,
					urls: imgLists,
					indicator: 'number',
					longPressActions: {
						itemList: ['发送给朋友', '保存图片', '收藏'],
						success: function(res) {},
						fail: function(res) {}
					}
				});
			},
			//  选择并发送图片
			getImage() {
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera '], //从相册选择
					success: (res) => {
						uni.showLoading({
							title: '图片发送中',
							mask: true,
						})
						let imgNum = res.tempFilePaths.length
						for (const item of res.tempFilePaths) {
							uploadFile(item)
								.then(imgRes => {
									imgNum--
									if (imgRes.status) {

										webSocket.sendSocketMessage({
												message: imgRes.data.url,
												msg_type: 2,
											})
											.then(resSoc => {
												this.toSaveMess(imgRes.data.url, 2, 1, true)
											})
											.catch(errSoc => {
												this.toSaveMess(imgRes.data.url, 2, 1, false)
												uni.showToast({
													title: '对方暂时不在线，请稍后再联系',
													icon: 'none'
												})
											})

									} else {
										uni.showToast({
											title: '图片发送失败',
											duration: 1500,
											icon: 'none'
										})
									}

									if (imgNum <= 0) {
										uni.hideLoading()
									}
								})
								.catch(err => {
									imgNum--
									uni.showToast({
										title: '图片发送失败',
										duration: 1500,
										icon: 'none'
									})
									if (imgNum <= 0) {
										uni.hideLoading()
									}
								})
						}
					}
				})
			},
			// 发送信息
			sendMess() {
				let tempIsSend = false
				if (this.mess) {
					webSocket.sendSocketMessage({
							message: this.mess,
							msg_type: 1,
						})
						.then(res => {
							tempIsSend = true
							this.toSaveMess(this.mess, 1, 1, tempIsSend)
							this.mess = null
							console.log(res, 'then')
						})
						.catch(err => {
							tempIsSend = false
							this.toSaveMess(this.mess, 1, 1, tempIsSend)
							this.mess = null
							uni.showToast({
								title: '对方暂时不在线，请稍后再联系',
								icon: 'none'
							})
							console.log(err, 'catch')
						})

				}
			},
			// 保存信息到缓存，同时将信息显示到屏幕
			toSaveMess(mess, type, userType, isSend) {
				let newMess = {
					message: mess, // 消息内容
					type: type, // 消息类型，1为文字，2为图片
					userType: userType, // 用户类型， 1为自己， 2为客服
					createTime: new Date().getTime(), // 发送时间
					isSend: isSend, // 是否发送成功
				}

				uni.getStorage({
					key: 'chatHistory',
					success: (res) => {
						let tempList = JSON.parse(JSON.stringify(res.data));
						console.log('toSaveMess')
						tempList.push(newMess)
						uni.setStorage({
							key: 'chatHistory',
							data: tempList,
							success: () => {}
						})
					},
					fail: (res) => {

						uni.setStorage({
							key: 'chatHistory',
							data: [newMess],
							success: () => {}
						})
					}
				})

				this.messList.push(newMess)
				this.scrollId = 'mess' + (this.messList.length - 1)
			},
			// 将未发送的信息重新发送
			reSend(index) {
				const mess = this.messList[index].message
				console.log(mess, index)
				webSocket.sendSocketMessage({
						message: mess,
						msg_type: 1,
					})
					.then(res => {
						this.$set(this.messList[index], 'isSend', true)
						const createTime = this.messList[index].createTime
						uni.getStorage({
							key: 'chatHistory',
							success: (resStorage) => {
								let tempMessList = resStorage.data
								for (let index in tempMessList) {
									if (tempMessList[index].createTime === createTime) {
										this.$set(tempMessList[index], 'isSend', true)
										uni.setStorage({
											key: 'chatHistory',
											data: tempMessList,
											success: () => {

											}
										})
									}
								}
							},
						})
						uni.showToast({
							title: '消息重发成功',
							icon: "success",
							duration: 1500,
						})
					})
					.catch(err => {
						this.$set(this.messList[index], 'isSend', false)
						uni.showToast({
							title: '消息重发失败',
							icon: "none",
							duration: 1500,
						})
					})
			},
			getNewMessage() {
				this.$api.getUserHistoryChat({
						isNoNeedLoading: true
					})
					.then(res => {
						if (res.status) {
							let tempList = []
							for (let index in res.data) {
								if (res.data.hasOwnProperty(index)) {
									if (parseInt(res.data[index].msg_type) === 10) {
										let tempNotice = {
											title: '红标消息',
											date: res.data[index].ctime,
											content: res.data[index].message,
											type: 3
										}
										tempList.push(tempNotice)
									} else {
										let tempItem = {
											message: res.data[index].message, // 消息内容
											type: res.data[index].msg_type, // 消息类型，1为文字，2为图片, 3为公告
											userType: 2, // 用户类型， 1为自己， 2为客服
											createTime: new Date().getTime(), // 发送时间
											isSend: true, // 是否发送成功
										}
										tempList.push(tempItem)
										// this.toSaveMess(res.data[index].message, res.data[index].msg_type, 2, true)
									}
								}
							}
							if (tempList.length > 0) {
								this.toSaveNewMess(tempList)
							}
						} else {}
					})
			},
			toSaveNewMess(data) {
				uni.getStorage({
					key: 'chatHistory',
					success: (res) => {
						let tempList = JSON.parse(JSON.stringify(res.data));
						uni.setStorage({
							key: 'chatHistory',
							data: tempList.concat(data),
							success: () => {}
						})
					},
					fail: (res) => {
						uni.setStorage({
							key: 'chatHistory',
							data: data,
							success: () => {}
						})
					}
				})
				
				this.messList = this.messList.concat(data)
				this.scrollId = 'mess' + (this.messList.length - 1)
			},
			setInter() {
				clearInterval(inter)
				inter = setInterval(() => {
					this.getNewMessage()
				}, 15000)
			},
		},
		onLoad() {
			if (!webSocket) {
				webSocket = new WebSocket()
			}
			this.getNewMessage()
			const selfID = this.$store.getters.getUserInfo.account_id
			webSocket.initWebSocket((res) => {
				this.toSaveMess(res.message, parseInt(res.msg_type), 2, true)
			}, selfID)
			this.messageNum = 6
			if (this.messList.length <= 0) {
				this.getHis(false)
					.then(() => {
						this.messageNum = 6
						if (this.messList.length > 0) {
							this.scrollId = 'mess' + (this.messList.length - 1)
						}
					})
					.catch(() => {
						this.messageNum = 6
						if (this.messList.length > 0) {
							this.scrollId = 'mess' + (this.messList.length - 1)
						}
					})
			}

		},
		onShow() {
			this.setInter()
		},
		onHide() {
			clearInterval(inter)
		},
		onUnload() {
			clearInterval(inter)
			webSocket.setSelfClose(true)
			webSocket.setLockReconnect(true)
			webSocket.closeConnect({
					reason: '正常关闭',
					code: 1000,
				})
				.then(res => {
					webSocket = null
					console.log(res, '关闭连接')
				})
				.catch(err => {
					console.log(err, '关闭连接错误')
				})
		},
		components: {
			hbtime,
			hbNotice,
			chatBox,
			chatImg,
			MescrollUni,
		},
		onShareAppMessage: (options) => {
			// 设置菜单中的转发按钮触发转发事件时的转发内容
			var shareObj = {
				title: "红标HONBIAO", // 默认是小程序的名称(可以写slogan等)
				path: '/pages/indexPage/authorization/authorization', // 默认是当前页面，必须是以‘/’开头的完整路径
				imageUrl: '/static/index/labelRouge.png', //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
				success: (res) => {
					// 转发成功之后的回调
					if (res.errMsg == 'shareAppMessage:ok') {}
				},
				fail: () => {
					// 转发失败之后的回调
					if (res.errMsg == 'shareAppMessage:fail cancel') {
						// 用户取消转发
					} else if (res.errMsg == 'shareAppMessage:fail') {
						// 转发失败，其中 detail message 为详细失败信息
					}
				}
			};
			return shareObj
		},
	}
</script>

<style scoped>
	.pageAll {
		box-sizing: border-box;
		background-color: #fdf5f3;
		width: 100%;
		height: 100%;
		display: inline-block;
		position: fixed;
		/* overflow-y: hidden; */
	}

	.scrollView {
		height: 93%;
		padding: 0 17upx;
		box-sizing: border-box;
		-webkit-overflow-scrolling: touch;
	}

	.bottomView {
		height: 7%;
		background-color: #FFF;
		box-shadow: 0 -15upx 40upx -30upx #4c3128;
		display: flex;
		flex-wrap: nowrap;
		position: fixed;
		bottom: 0;
		width: 100%;
		z-index: 2000;
	}

	.bottomViewInput {
		width: 80%;
		padding: 17upx;
		display: inline-block;
		box-sizing: border-box;
	}

	.bottomViewInput input {
		background-color: #fdf5f3;
		width: 100%;
		/* height: 66.66upx; */
		height: 100%;
		border-radius: 15upx;
		display: inline-block;
		padding: 0 20upx;
		font-size: 32upx;
		color: #333333;
		box-sizing: border-box;
		margin-bottom: 17upx;
	}

	.bottomViewBtn {
		width: 20%;
		display: flex;
		flex-wrap: nowrap;
	}

	.bottomViewBtn image {
		width: 42.66upx;
		height: 42.66upx;
		margin: auto 0;
	}

	.bottomViewBtn button {
		color: #FFF;
		font-size: 24upx;
		background-color: #f7533e;
		font-weight: 200;
		width: 66.66upx;
		height: 42.66upx;
		margin: auto 0;
		margin-left: 10px;
		padding: 0;
		line-height: 42.66upx;
	}

	.bottomViewBtn button:after {
		border: none;
	}

	.subActive {
		background-color: #FF0000 !important;
	}

	.chatBox {
		padding: 30upx 0;
	}


	.scrollDown {
		position: relative;
		width: 100%;
		height: 0;
		overflow: hidden;
		text-align: center;
	}

	/* 下拉刷新,上拉加载--提示文本 */
	.scrollDown .downwarp-tip {
		display: inline-block;
		font-size: 28upx;
		color: gray;
		vertical-align: middle;
	}

	/* 下拉刷新--高度重置的过渡动画 */
	.scroll-downwarp-reset {
		-webkit-transition: height 1000ms;
		transition: height 1000ms;
	}

	/* 下拉刷新,上拉加载--旋转进度条 */
	.scrollDown .downwarp-progress {
		display: inline-block;
		width: 32upx;
		height: 32upx;
		border-radius: 50%;
		border: 2upx solid gray;
		border-bottom-color: transparent;
		vertical-align: middle;
	}

	/* 旋转动画 */
	.scroll-rotate {
		-webkit-animation: mescrollRotate 0.6s linear infinite;
		animation: mescrollRotate 0.6s linear infinite;
	}

	@-webkit-keyframes mescrollRotate {
		0% {
			-webkit-transform: rotate(0deg);
		}

		100% {
			-webkit-transform: rotate(360deg);
		}
	}

	@keyframes mescrollRotate {
		0% {
			transform: rotate(0deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}
</style>
